// ************************************************************************
// Class      PHPTube
// Version:   0.1.7
// Date:      2008/08/10
// Author:    Michael Kamleitner (michael.kamleitner@gmail.com)
// WWW:       http://www.kamleitner.com/code
//            (suggestions, bug-reports & general shouts are welcome)
// Copyright: copyright 2007 - Michael Kamleitner
//
//            This file is part of PHPTube
//
//            PHPTube is free software; you can redistribute it and/or modify
//            it under the terms of the GNU General Public License as published by
//            the Free Software Foundation; either version 2 of the License, or
//            (at your option) any later version.
//
//            PHPTube is distributed in the hope that it will be useful,
//            but WITHOUT ANY WARRANTY; without even the implied warranty of
//            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//            GNU General Public License for more details.
//
//            You should have received a copy of the GNU General Public License
//            along with PHPTube; if not, write to the Free Software
//            Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//            
// ************************************************************************

// adapted from PHPtube by Gareth Williams 

package com.gw.youTubeAudioAPI.phpTube {

	import com.gw.youTubeAudioAPI.phpTube.HTTP_Request.*;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	
	public class PHPTube extends EventDispatcher{
		
		public static var debug:Boolean = false;
		private var req:HTTP_Request; 
		
		// Function:	download		... Download any Video-Clip from YouTube
		// Paramters:	$video_id		... Video-ID as given in YouTube URL (f.e. the Video at http://youtube.com/watch?v=TWZ5j-SNVKs
		//									has the ID "TWZ5j-SNVKs"
		//				$video_filename ... local path+filename, the video is downloaded to (check write-permissions!)

		public function PHPTube():void
		{
			super();
		}
		public function download (video_id:String):void{
			var url:String = "http://www.youtube.com/watch?v="+video_id;
			this.req = new HTTP_Request(url);
			var response:Object = this.req.sendRequest();//should really be implemented using event listeners - even with the original pear class
			if (response.isError) 
				throw new Error(response.getMessage(),"\n");
			else
				req.addEventListener(Event.COMPLETE, this.onPage);//wait for header to return page data
		}
		//utility functions - gw
		private function onPage(evt:Event):void {
			
			var page:String = String(this.req.getResponseBody());	
			
			//preg_match('/watch_fullscreen\?video_id=(.*?)&l=(.*?)+&t=(.*?)&/', $page, $match); //..?
			var vidID:RegExp = /"video_id": "(.*?)"/gi;
			var match:Array = vidID.exec(page);
			var var_id:String = match[1];//second parenthetical subgroup
			
			var trackingID:RegExp = /"t": "(.*?)"/g;
			match = trackingID.exec(page);
			var var_t:String = match[1];
			
			var url:String = "";
			url	+=	var_id;
			url +=	"&t=";
			url +=	var_t;
			url =	"http://www.youtube.com/get_video?video_id="+url;
			if (debug)
				trace(url,"\n");
			req = new HTTP_Request	(url, {"allowRedirects":true, 
									 "maxRedirects":99, 
									 "type":HTTP_Request.HTTP_REQUEST_TYPE_BIN});
			req.setMethod(HTTP_Request.HTTP_REQUEST_METHOD_GET);
			req.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");	
			var response:Object = req.sendRequest();
			if (response.isError)
				throw new Error("Error: Failed to open YouTube-Source\n");
			else
				req.addEventListener(Event.COMPLETE, onFLVData);//listen for data streaming
		}
		private function onFLVData(evt:Event):void {
			//dispatch event
			trace("flv loaded");
			dispatchEvent(new PHPTubeEvent(PHPTubeEvent.FLV_DOWNLOADED, ByteArray(this.req.getResponseBody())));
		}
	}
}
